﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SG.Logic;
using SG.UI.Models;
using SG.Domain;

namespace SG.UI.Controllers
{
    public class VentaController : Controller
    {
        ExpVenta exp = new ExpVenta();
       
        //
        // GET: /Venta/

        public ActionResult Index()
        {
            return View(exp.GetAllVenta());
        }

      
        //
        // GET: /Venta/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Venta/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                Venta entity = new Venta();
                entity.Cliente = collection["Cliente"];
                if (entity.Cliente == "")
                    throw new Exception("Debe ingresar un cliente.");

                entity.Fecha = DateTime.Now;
                if (collection["IdArticulo"] != null)
                {
                    string[] idArticuloList = collection["IdArticulo"].Split(',');
                    string[] cantidadList = collection["Cantidad"].Split(',');

                    for (int i = 0; i < idArticuloList.Length; i++)
                    {
                        ArticuloVenta av = new ArticuloVenta();
                        av.Cantidad = int.Parse(cantidadList[i]);
                        av.IdArticulo = int.Parse(idArticuloList[i]);
                        entity.ArticuloVenta.Add(av);
                    }
                }
                else
                    throw new Exception("Debe seleccionar al menos un artículo.");

                exp.SaveVenta(entity);
                return RedirectToAction("Index");
                
            }
            catch (Exception ex)
            {
                TempData["VMAlert"] = new VMAlert() { Title = "Err", Body = ex.Message };
                return View();
            }
        }
        
       
        //
        // GET: /Venta/Delete/5
 
        public ActionResult Details(int id)
        {
            Venta venta=exp.GetVenta(id);
            TempData["Cliente"] = venta.Cliente;
            TempData["Fecha"] = venta.Fecha;

            return View(exp.GetAllArticuloVenta(id));
        }

       
    }
}
